package thread;

import java.util.PriorityQueue;

class MyTimeTask2 implements Comparable<MyTimeTask2>{
    private Runnable runnable;
    private long time;

    public  MyTimeTask2(Runnable runnable, long delay) {
        this.runnable = runnable;
        this.time = System.currentTimeMillis() + delay;
    }

    public Runnable getRunnable() {
        return runnable;
    }

    public Long getTime() {
        return time;
    }

    @Override
    public int compareTo(MyTimeTask2 o) {
        return (int) (this.time - o.time);
    }
}
 class MyTimer2 {

    private PriorityQueue<MyTimeTask2> queue = new PriorityQueue<>();
    private Object locker = new Object();

    public void schedule(Runnable runnable, long delay) {
        synchronized (locker) {
            queue.offer(new MyTimeTask2(runnable, delay));
            locker.notify();
        }
    }

    public MyTimer2() {
        Thread t = new Thread(() -> {
            while (true) {
                try {
                    synchronized(locker) {
                        while (queue.isEmpty()) {
                            locker.wait();
                        }

                        MyTimeTask2 task = queue.peek();
                        long curTime = System.currentTimeMillis();
                        if (curTime >= task.getTime()) {

                            task.getRunnable().run();
                            queue.poll();
                        } else {
                            locker.wait(task.getTime() - curTime);
                        }
                    }
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        t.start();
    }
}

public class MyTimerDemo {

    public static void main(String[] args) {
        MyTimer2 timer = new MyTimer2();
        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("2000");
            }
        }, 2000);

        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("4000");
            }
        }, 4000);

        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("1000");
            }
        }, 1000);

        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("3000");
            }
        }, 3000);

        System.out.println("程序开始");

    }



}
